<template>
  <view class="account_wrapper">
    <top-tab-nav :list="topTabList" :current="current" @change="changeTab"></top-tab-nav>
    <not-login v-if="!userInfo"></not-login>
    <div v-else>
      <account-info v-if="current === 0" :pageCurrent="current" ref="accountInfoRef"></account-info>
      <ticket v-else-if="current === 1" ref="ticketRef"></ticket>
      <order v-else-if="current === 2" ref="orderRef"></order>
      <about v-else ref="aboutRef"></about>
    </div>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineProps, watch, computed } from 'vue'
import { useStore } from 'vuex'

import NotLogin from './components/notlogin/notlogin.vue'
import AccountInfo from './components/accountInfo/accountInfo.vue'
import Ticket from './components/ticket/ticket.vue'
import Order from './components/order/order.vue'
import About from './components/about/about.vue'

const store = useStore()
const userInfo = computed(() => store.state.user.userInfo)
console.log('缓存中的userInfo：', userInfo.value)
// 定义子组件的 ref
const accountInfoRef = ref()
const ticketRef = ref()
const orderRef = ref()
const aboutRef = ref()
const props = defineProps({
  currentTab: {
    type: Number,
    default: 0
  }
})

watch(
  () => props.currentTab,
  (newVal) => {
    console.log('子组件的currentTab', newVal)
    changeTab(newVal)
  }
)
interface TabItem {
  id: number
  cn: string
  en: string
}
const topTabList = reactive<TabItem[]>([
  {
    id: 0,
    cn: '账户',
    en: 'Account'
  },
  {
    id: 1,
    cn: '票务',
    en: 'Ticket'
  },
  {
    id: 2,
    cn: '订单',
    en: 'Order'
  },
  {
    id: 3,
    cn: '关于我们',
    en: 'About'
  }
])

const current = ref<number>(0)

const changeTab = (index: number) => {
  console.log('个人中心的选项切换', index)
  current.value = index
  uni.setStorageSync('currentTopTab', index)
  // 根据 tab 切换调用对应子组件的方法
  if (index !== 0) {
    accountInfoRef.value.closeCode()
  }
  switch (index) {
    case 0:
      if (accountInfoRef.value) {
        accountInfoRef.value.initData()
      }
      break
    case 1:
      if (ticketRef.value) {
        ticketRef.value.initData()
      }
      break
    case 2:
      if (orderRef.value) {
        orderRef.value.reload()
      }
      break
    case 3:
      if (aboutRef.value) {
        aboutRef.value.initData()
      }
      break
  }
}
onMounted(() => {
  current.value = props.currentTab
  console.log('子组件的currentTab', typeof current.value)
  changeTab(current.value)
})
// 如果你需要手动调用某个子组件方法，可以直接触发
</script>
